package com.dean.netty.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class DeanNettyServer {
    // EventLoopGroup 事件循环组 用户监听及建立连接
    private final EventLoopGroup serverGroup = new NioEventLoopGroup();
    private final EventLoopGroup clientGroup = new NioEventLoopGroup();
    // 服务端启动初始化
    private final ServerBootstrap serverBootstrap = new ServerBootstrap();
    // 1、将serverGroup和clientGroup注册到服务端的Channel上；
    // 2、注册一个服务端的初始化器MyNettyServerInitializer；
    // 3、该初始化器中的initChannel()方法会在连接被注册到Channel后立刻执行；
    // 5、最后将端口号绑定到8080；
    public void start() throws InterruptedException {
        ChannelFuture channelFuture = serverBootstrap.group(serverGroup,clientGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new DeanNettyServerInit()).bind(8080)
                .sync();
        channelFuture.channel().closeFuture().sync();
        serverGroup.shutdownGracefully();
        clientGroup.shutdownGracefully();
    }

    public static void main(String[] args) {
        DeanNettyServer server = new DeanNettyServer();
        try {
            server.start();
        } catch (InterruptedException e) {
            System.out.println("聊天服务器启动失败");
            e.printStackTrace();
        }
    }

}
